package library.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import library.domain.Book;
import library.frames.DownloadsFrame;

public class DownloadThread extends Thread {

    private final ObjectInputStream input;
    private final File file;

    public DownloadThread(ObjectInputStream input, File file) {
        this.input = input;
        this.file = file;
    }

    @Override
    public void run() {
        Download d = new Download(file.getName(), DownloadState.IN_PROGRESS);
        DownloadsFrame.getInstance().addNewDownload(d);
        try {            
            Book b = (Book) input.readObject();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = new byte[b.getSize().intValue()];
            for (int i = 0; i < b.getSize().intValue(); ++i) {
                bytes[i] = b.getContent()[i];
            }
            fos.write(bytes);
            fos.close();
            d.setState(DownloadState.COMPLETED);
            DownloadsFrame.getInstance().updateStatus();
        } catch (Exception e) {
            d.setState(DownloadState.TERMINATED);
            DownloadsFrame.getInstance().updateStatus();
        }
    }
}
